<template>
  <div class="customer-management">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span>客户管理 /</span>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="showAddModal = true">+ 添加客户</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="客户姓名：">
          <el-input v-model="searchForm.name" placeholder="请输入客户姓名" style="width: 200px;"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号：">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" style="width: 200px;"></el-input>
        </el-form-item>
        
        <el-form-item label="渠道来源：">
          <el-select v-model="searchForm.channel" placeholder="请选择" clearable style="width: 200px;">
            <el-option v-for="option in channelOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="意向学科：">
          <el-select v-model="searchForm.subject" placeholder="请选择" clearable style="width: 200px;">
            <el-option v-for="option in subjectOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="customerList" style="width: 100%" height="50vh" border stripe>
        <el-table-column prop="id" label="序号" width="80"></el-table-column>
        <el-table-column prop="name" label="客户姓名" width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column prop="channel" label="渠道来源" width="120">
          <template #default="scope">
            {{ formatChannel(scope.row.channel) }}
          </template>
        </el-table-column>
        <el-table-column prop="subject" label="意向学科" width="180">
          <template #default="scope">
            {{ formatSubject(scope.row.subject) }}
          </template>
        </el-table-column>
        <el-table-column prop="courseName" label="意向课程"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 查看详情模态框 -->
    <el-dialog v-model="viewModalVisible" title="客户详情" width="600px" destroy-on-close>
      <div class="detail-info">
        <div class="detail-row">
          <div class="detail-item">
            <span class="label">客户姓名：</span>
            <span class="value">{{ currentCustomer.name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">手机号：</span>
            <span class="value">{{ currentCustomer.phone }}</span>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-item">
            <span class="label">渠道来源：</span>
            <span class="value">{{ formatChannel(currentCustomer.channel) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">性别：</span>
            <span class="value">{{ formatGender(currentCustomer.gender) }}</span>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-item">
            <span class="label">意向学科：</span>
            <span class="value">{{ formatSubject(currentCustomer.subject) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">年龄：</span>
            <span class="value">{{ currentCustomer.age || '-' }}</span>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-item">
            <span class="label">意向课程：</span>
            <span class="value">{{ currentCustomer.courseName || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">学历：</span>
            <span class="value">{{ formatDegree(currentCustomer.degree) }}</span>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-item">
            <span class="label">微信：</span>
            <span class="value">{{ currentCustomer.wechat || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">QQ：</span>
            <span class="value">{{ currentCustomer.qq || '-' }}</span>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-item">
            <span class="label">就业状态：</span>
            <span class="value">{{ formatJobStatus(currentCustomer.jobStatus) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(currentCustomer.createTime) }}</span>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-item full-width">
            <span class="label">客户备注：</span>
            <span class="value">{{ currentCustomer.remark || '暂无备注' }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="viewModalVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加客户模态框 -->
    <el-dialog v-model="showAddModal" title="添加客户" width="600px" destroy-on-close>
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item label="手机号：" prop="phone" required>
          <el-input v-model="addForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名：" prop="name" required>
          <el-input v-model="addForm.name" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
        <el-form-item label="渠道来源：" prop="channel">
          <el-select v-model="addForm.channel" placeholder="请选择" style="width: 100%;">
            <el-option v-for="option in channelOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学历：" prop="degree">
          <el-select v-model="addForm.degree" placeholder="请选择" style="width: 100%;">
            <el-option v-for="option in degreeOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别：" prop="gender">
          <el-select v-model="addForm.gender" placeholder="请选择" style="width: 100%;">
            <el-option v-for="option in genderOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄：" prop="age">
          <el-input v-model.number="addForm.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="微信：" prop="wechat">
          <el-input v-model="addForm.wechat" placeholder="请输入客户微信号"></el-input>
        </el-form-item>
        <el-form-item label="QQ：" prop="qq">
          <el-input v-model="addForm.qq" placeholder="请输入客户QQ号"></el-input>
        </el-form-item>
        <el-form-item label="在职状态：" prop="jobStatus">
          <el-select v-model="addForm.jobStatus" placeholder="请选择" style="width: 100%;">
            <el-option v-for="option in jobStatusOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="意向学科：" prop="subject">
          <el-select v-model="addForm.subject" placeholder="请选择" style="width: 100%;" :disabled="!this.addForm.channel">
            <el-option v-for="option in subjectOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="意向课程：" prop="courseId">
          <el-select v-model="addForm.courseId" placeholder="请选择" style="width: 100%;" :disabled="!this.addForm.subject">
            <el-option v-for="option in courseOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddModal = false">取消</el-button>
        <el-button type="primary" @click="submitAddCustomer">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑客户模态框 -->
    <el-dialog v-model="editModalVisible" title="编辑客户" width="600px" destroy-on-close>
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名：" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
        <el-form-item label="渠道来源：" prop="channel">
          <el-select v-model="editForm.channel" placeholder="请选择" style="width: 100%;">
            <el-option v-for="option in channelOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学历：" prop="degree">
          <el-select v-model="editForm.degree" placeholder="请选择" style="width: 100%;">
            <el-option v-for="option in degreeOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别：" prop="gender">
          <el-select v-model="editForm.gender" placeholder="请选择" style="width: 100%;">
            <el-option v-for="option in genderOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄：" prop="age">
          <el-input v-model.number="editForm.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="微信：" prop="wechat">
          <el-input v-model="editForm.wechat" placeholder="请输入微信号"></el-input>
        </el-form-item>
        <el-form-item label="QQ：" prop="qq">
          <el-input v-model="editForm.qq" placeholder="请输入QQ号"></el-input>
        </el-form-item>
        <el-form-item label="在职状态：" prop="jobStatus">
          <el-select v-model="editForm.jobStatus" placeholder="请选择" style="width: 100%;">
            <el-option v-for="option in jobStatusOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="意向学科：" prop="subject">
          <el-select v-model="editForm.subject" placeholder="请选择" style="width: 100%;" :disabled="!this.editForm.channel">
            <el-option v-for="option in subjectOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="意向课程：" prop="courseId">
          <el-select v-model="editForm.courseId" placeholder="请选择" style="width: 100%;" :disabled="!this.editForm.subject">
            <el-option v-for="option in editFormCourseOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editModalVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditCustomer">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCustomerList, addCustomer, getCustomerById, updateCustomer } from '../api/customer'
import { 
  degreeOptions, jobStatusOptions,
  formatChannel, formatSubject, formatGender, formatDegree, formatJobStatus,
  isValidPhone
} from '../utils/sysUtils'
import { useCustomerStore } from '../stores/customer'
import { useCourseStore } from '../stores/course'

export default {
  name: 'CustomerView',
  data() {
    return {
      customerStore: null,
      courseStore: null,
      // 搜索表单
      searchForm: {
        phone: '',
        name: '',
        channel: '',
        subject: ''
      },
      // 客户列表
      customerList: [],
      // 分页数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 模态框状态
      viewModalVisible: false,
      showAddModal: false,
      editModalVisible: false,
      // 当前客户
      currentCustomer: {},
      // 添加表单
      addForm: {
        name: '',
        phone: '',
        channel: '',
        gender: '',
        age: '',
        wechat: '',
        qq: '',
        degree: '',
        jobStatus: '',
        subject: '',
        courseId: '',
        remark: ''
      },
      // 编辑表单
      editForm: {
        id: '',
        name: '',
        phone: '',
        channel: '',
        gender: '',
        age: '',
        wechat: '',
        qq: '',
        degree: '',
        jobStatus: '',
        subject: '',
        courseId: '',
        remark: ''
      },
      // 验证规则
      addRules: {
        name: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: this.validatePhone, trigger: 'blur' }
        ]
      },
      editRules: {
        name: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: this.validatePhone, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 初始化时加载数据
    this.loadCustomerList()
    // 初始化stores
    this.customerStore = useCustomerStore()
      this.courseStore = useCourseStore()
    },
  // 监听学科变化，清除课程选择
  watch: {
    'addForm.subject'(newVal) {
      if (newVal !== undefined && newVal !== null) {
        this.addForm.courseId = ''
      }
    },
    'editForm.subject'(newVal) {
      if (newVal !== undefined && newVal !== null) {
        this.editForm.courseId = ''
      }
    }
  },
  computed: {
    channelOptions() {
      return this.customerStore.getChannels
    },
    subjectOptions() {
      return this.customerStore.getSubjects
    },
    // 只显示男和女的性别选项
    genderOptions() {
      return [
        { label: "男", value: 1 },
        { label: "女", value: 0 }
      ]
    },
    degreeOptions() {
      return degreeOptions
    },
    jobStatusOptions() {
      return jobStatusOptions
    },
    // 计算属性 - 根据当前选择的学科获取课程列表（新增表单）
    courseOptions() {
      if (!this.addForm.subject) return []
      const courses = this.courseStore.getCoursesBySubject?.(this.addForm.subject) || []
      return courses.map(course => ({
        label: course.name,
        value: course.id
      }))
    },
    // 计算属性 - 根据当前选择的学科获取课程列表（编辑表单）
    editFormCourseOptions() {
      if (!this.editForm.subject) return []
      const courses = this.courseStore.getCoursesBySubject?.(this.editForm.subject) || []
      return courses.map(course => ({
        label: course.name,
        value: course.id
      }))
    }
  },
  methods: {
    // 验证手机号
    validatePhone(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!isValidPhone(value)) {
        callback(new Error('请输入有效的手机号'))
      } else {
        callback()
      }
    },
    // 格式化函数
    formatChannel,
    formatSubject,
    formatGender,
    formatDegree,
    formatJobStatus,
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    // 加载客户列表
    async loadCustomerList() {
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        
        const response = await getCustomerList(params)
        
        if (response.code === 1) {
          this.customerList = response.data.rows
          this.total = response.data.total
        } else {
          this.$message.error(response.msg || '获取客户列表失败')
        }
      } catch (error) {
        this.$message.error('获取客户列表失败，请稍后重试')
      }
    },
    // 搜索
    search() {
      this.currentPage = 1
      this.loadCustomerList()
    },
    // 重置
    reset() {
      this.searchForm = {
        phone: '',
        name: '',
        channel: '',
        subject: ''
      }
      this.currentPage = 1
      this.loadCustomerList()
    },
    // 查看详情
    async handleView(item) {
      try {
        const response = await getCustomerById(item.id)
        if (response.code === 1) {
          this.currentCustomer = response.data
          this.viewModalVisible = true
        } else {
          this.$message.error(response.msg || '获取客户详情失败')
        }
      } catch (error) {
        this.$message.error('获取客户详情失败，请稍后重试')
      }
    },
    // 编辑客户
    handleEdit(item) {
      // 从Pinia获取客户数据（这里直接使用传入的item，实际项目中可以从store获取）
      this.editForm = { ...item }
      this.editModalVisible = true
    },
    // 提交添加客户
    async submitAddCustomer() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const response = await addCustomer(this.addForm)
            if (response.code === 1) {
              this.showAddModal = false
              this.$message.success('客户添加成功')
              this.$refs.addFormRef.resetFields()
              this.loadCustomerList()
            } else {
              this.$message.error(response.msg || '添加客户失败')
            }
          } catch (error) {
            this.$message.error('添加客户失败，请稍后重试')
          }
        }
      })
    },
    // 提交编辑客户
    async submitEditCustomer() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 创建一个新对象，不包含createTime和updateTime字段
            const customerData = {
              ...this.editForm
            }
            // 删除不需要传递的时间字段
            delete customerData.createTime
            delete customerData.updateTime
            
            const response = await updateCustomer(customerData)
            if (response.code === 1) {
              this.editModalVisible = false
              this.$message.success('客户编辑成功')
              this.loadCustomerList()
            } else {
              this.$message.error(response.msg || '编辑客户失败')
            }
          } catch (error) {
            this.$message.error('编辑客户失败，请稍后重试')
          }
        }
      })
    },
    // 分页处理
    handleSizeChange(size) {
      this.pageSize = size
      this.loadCustomerList()
    },
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadCustomerList()
    }
  }
}
</script>

<style scoped>
/* 页面容器 */
.customer-view {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 操作按钮区域 */
.action-buttons {
  margin-bottom: 15px;
}

/* 表格容器样式 */
.table-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

/* 分页区域样式 */
.pagination {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 15px;
  margin-bottom: 20px;
}

/* 详情页样式 */
.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item .detail-label {
  width: 100px;
  color: #909399;
  text-align: right;
  margin-right: 20px;
}

.detail-item .detail-value {
  flex: 1;
  word-break: break-word;
}

/* 表单行样式 */
.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.form-row .el-form-item {
  margin-right: 20px;
}
</style>